package org.elastic.compreplatform.crawler.core.elasticsearch;

import java.net.URLEncoder;
import java.util.Map;

import org.elastic.compreplatform.common.util.HttpClientUtil;
import org.elastic.compreplatform.conf.core.core.ConfZkConf;
import org.elastic.compreplatform.crawler.model.XvideosResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.minstone.quartz.core.util.SpringConfigurerUtil;

/**
 * ClassName: ESqlTemplate 
 * @Description: Elasticsearch sql操作模板
 * 索引操作API：
 * low level https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/java-rest-low.html
 * high level https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/java-rest-high.html
 * @author JornTang
 * @date 2017年12月21日
 */
public class ESqlTemplate {
	private static Logger log = LoggerFactory.getLogger(ESqlTemplate.class);
	private static String es_url = "127.0.0.1:9200";//ConfZkConf.get("elastic_compre.es.url");
	/**
	 * @Description: 根据sql查询结果
	 * @param sql
	 * @param bean
	 * @return   
	 * @return T  
	 * @throws Exception 
	 * @throws
	 * @author JornTang
	 * @date 2017年12月27日
	 */
	public static <T> T searchBySql(String sql, T bean) throws Exception{
		String url = "http://"+es_url.split(",")[0]+"/_sql?sql=";
		String _sql = URLEncoder.encode(sql,"UTF-8");
		String result=HttpClientUtil.get(url+_sql);
		return (T) JSON.parseObject(result, XvideosResultMapper.class);
	}
	/**
	 * @Description: 根据sql查询结果
	 * @param sql
	 * @param bean
	 * @return   
	 * @return T  
	 * @throws Exception 
	 * @throws
	 * @author JornTang
	 * @date 2017年12月27日
	 */
	public static XvideosResultMapper searchBySql(String sql) throws Exception{
		String url = "http://"+es_url.split(",")[0]+"/_sql?sql=";
		String _sql = URLEncoder.encode(sql,"UTF-8");
		String result=HttpClientUtil.get(url+_sql);
		return JSON.parseObject(result, XvideosResultMapper.class);
	}
	
	/**
	 * @Description: 根据sql查询结果
	 * @param sql
	 * @param fieldName
	 * @return
	 * @throws Exception   
	 * @return XvideosResultMapper  
	 * @throws
	 * @author JornTang
	 * @date 2018年1月16日
	 */
	public static long searchBySql(String sql,String fieldName) throws Exception{
		String url = "http://"+es_url.split(",")[0]+"/_sql?sql=";
		String _sql = URLEncoder.encode(sql,"UTF-8");
		log.info("es searchBySql:【{}】", _sql);
		String result=HttpClientUtil.get(url+_sql);
		XvideosResultMapper mapper = JSON.parseObject(result, XvideosResultMapper.class);
		Map<String,Object> aggMap = mapper.getAggregations();
		Map<String,Object> map = (Map<String,Object>)aggMap.get(fieldName);
		return Double.valueOf(map.get("value").toString()).longValue();
	}
	public static void main(String[] args) {
		try {
			String sql= "select count(*) as count from xvideos";
			long lo = searchBySql(sql, "count");
			System.err.println(lo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
